package com.me.study.jdk8.functionInterface;

import org.junit.Test;

import java.util.function.Consumer;

/**
 * JDK 内置的函数式接口--消费型：Consumer 接口<p>
 *     特点：只进不出，作为方法/构造参数
 *
 * @author ME
 * @date   2019/12/17
 */
public class TestConsumer {

    @Test
    public void testAccept1() {
        System.out.println("\ntestAccept1():");

        Consumer<String> consumer = (str) -> System.out.println("hello " + str);
        consumer.accept("Tom1!");
    }

    @Test
    public void testAccept2() {
        System.out.println("\ntestAccept2():");

        doSomething("Tom2!", str -> System.out.println("hello " + str));
    }

    public void doSomething(String str, Consumer<String> consumer) {
        consumer.accept(str);
    }

    /**
     * 默认方法 andThen():
     * <p>整合两个 Consumer, 顺序执行</p>
     *
     */
    @Test
    public void testAndThen() {
        System.out.println("\ntestAndThen():");

        String arr = "Tom,10";
        Consumer<String> consumer = (str) -> {
            System.out.println("name: " + str.split(",")[0]);
        };
        consumer.andThen(str -> {
            System.out.println("age: " + str.split(",")[1]);
        }).accept(arr);
    }

    @Test
    public void testAndThen2() {
        System.out.println("\ntestAndThen2():");

        String[] arr = { "Tom,10", "Jack,11" };
        method(arr, str -> {
            System.out.println("name: " + str.split(",")[0]);
        }, str -> {
            System.out.println("age: " + str.split(",")[1]);
        });
    }

    public void method(String[] arr, Consumer<String> consumer1,Consumer<String> consumer2){
        for (String str : arr) {
            //使用 andThen方法, 把两个Consumer接口连接到一起,在消费数据
            //con1连接con2, 先执行con1消费数据,在执行con2消费数据
            consumer1.andThen(consumer2).accept(str);
        }
    }
}
